package com.toro.utils;

import com.toro.domain.User;

import java.lang.reflect.Field;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName: JDBCUtils
 * @Description:
 * @Author: ToroLHZ
 * @Date: 2023/12/17 15:33
 */
public class JDBCUtils {
    //获取数据库连接
    public static Connection getConnection() {
        //1、读取配置文件的基本信息
//        InputStream is = ClassLoader.getSystemClassLoader().getResourceAsStream("com/atWYQ/connect/jdbc.properties");

//        Properties pros = new Properties();
//        try {
//            pros.load(is);
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//
//        String user = pros.getProperty("user");
//        String password = pros.getProperty("password");
//        String url = pros.getProperty("url");
//        String driver = pros.getProperty("driver");

        String user = "root";
        String password = "123456";
        String url = "jdbc:mysql://localhost:3307/netty_chat?useSSL=false&characterEncoding=utf-8&serverTimezone=Hongkong";
        String driver = "com.mysql.cj.jdbc.Driver";
        //2、加载驱动
        try {
            Class.forName(driver);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }

        //3、获取链接
        Connection connection = null;
        try {
            connection = DriverManager.getConnection(url, user, password);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return connection;
    }

    //关闭资源
    public static void closeResource(Connection connection, PreparedStatement ps) {
        try {
            if (ps != null) {
                ps.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        try {
            if (connection != null) {
                connection.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    //关闭资源
    public static void closeResource(Connection connection, PreparedStatement ps, ResultSet rs) {
        try {
            if (ps != null) {
                ps.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        try {
            if (connection != null) {
                connection.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    //通用增删改操作方法，只需传入sql语句，以及占位符参数
    public static void update(String sql, Object... args) {
        Connection connection = null;
        PreparedStatement ps = null;
        try {
            //1、获取连接(获取链接的JDBCUtils工具代码在后面已经给出)
            connection = JDBCUtils.getConnection();
            //2、预编译sql语句
            ps = connection.prepareStatement(sql);
            //3、填充占位符
            for (int i = 0; i < args.length; i++) {
                ps.setObject(i + 1, args[i]); //注意要i+1
            }
            //4、执行操作
            ps.execute();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            //5、资源关闭（具体工具类代码在后面已经给出）
            JDBCUtils.closeResource(connection, ps);
        }
    }

    //通用的查询操作
    public static <T> List<T> queryInstance(Class<T> clazz, String sql, Object... args) {
        Connection connection = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        List<T> list = new ArrayList<>();
        try {
            //获取连接
            connection = JDBCUtils.getConnection();
            //预编译sql语句
            ps = connection.prepareStatement(sql);
            //填充占位符
            for (int i = 0; i < args.length; i++) {
                ps.setObject(i + 1, args[i]);
            }
            //执行查询返回结果集
            rs = ps.executeQuery();
            ResultSetMetaData metaData = rs.getMetaData();
            //获取查询列数
            int columnCount = metaData.getColumnCount();

            while (rs.next()) {
                T t = clazz.newInstance();

                for (int i = 0; i < columnCount; i++) {
                    //获取返回值
                    Object columnValue = rs.getObject(i + 1);
                    //获取该返回值的标签名
                    String columnLabel = metaData.getColumnLabel(i + 1);
                    //通过反射进行封装
                    Field field = clazz.getDeclaredField(columnLabel);
                    field.setAccessible(true);
                    field.set(t, columnValue);
                }
                list.add(t);
            }
            return list;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //关闭资源
            JDBCUtils.closeResource(connection, ps, rs);
        }
        return null;
    }

    //增、删、改
    public void test01() {
        //更新
        String sql = "update author set id = ? where id = ?";
        update(sql, 10, 3);

        //删除
        sql = "delete from author where id = ?";
        update(sql, 10);

        //添加
        sql = "insert into author values(?, ?, ?)";
        update(sql, 3, "WYQ", "中国");
    }

    //查
    public void test02() {
        String sql = "select * from user";
        List<User> authors = queryInstance(User.class, sql);//通过范型来判断返回值，因此第一个参数需传入要查询类的类型
        if (authors != null) {
            authors.forEach(System.out::println);
        }


        sql = "select * from user where user = ?";
        authors = queryInstance(User.class, sql, "zhangsan");//通过范型来判断返回值，因此第一个参数需传入要查询类的类型
        if (authors != null) {
            authors.forEach(System.out::println);
        }
    }


}
